package com.projectzqjz.parttimework.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;

import com.projectzqjz.parttimework.App;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class JpushSetAliasUtils {
    private Context context;

    public JpushSetAliasUtils(Context context) {
        this.context = context;
    }

    //设置极光推送别名
    public void setAlias(String alias) {
        boolean isSet = (boolean) SPUtils.get(App.getContext(), "isSet", false);
        // 调用 Handler 来异步设置别名
        if (!isSet)
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    SPUtils.put(App.getContext(), "isSet", true);
                    Log.e("setAlias", "设置别名成功！");
                    break;
                case 6002:
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;


    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull android.os.Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_SET_ALIAS) {// 调用 JPush 接口来设置别名。
                JPushInterface.setAliasAndTags(context.getApplicationContext(),
                        (String) msg.obj,
                        null,
                        mAliasCallback);
            }
        }
    };
}
